package com.ljfiction.book.tools;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringTool {

    public static boolean isContain(String str, String reg) {
        return str.contains(reg);

    }

    /**
     * "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
     *
     * @param mobiles
     * @return
     */
    public static boolean isMobileNO(String mobiles) {
        String telRegex = "[1][3456789]\\d{9}";
        if (TextUtils.isEmpty(mobiles)) {
            return false;
        } else {
            return mobiles.matches(telRegex);
        }


    }

    /**
     * "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
     *
     * @param mobiles
     * @return
     */
    public static boolean isMobileNONew(String mobiles) {
        String telRegex = "[1]\\d{10}";
        if (TextUtils.isEmpty(mobiles))
            return false;
        else
            return mobiles.matches(telRegex);

    }

    /**
     * 6-18位
     * 验证密码
     *
     * @param pass
     * @return
     */
    public static boolean isPass(String pass) {
        if (pass.length() < 6 || pass.length() > 18) {
            return false;
        }
        Pattern p = Pattern.compile("^[a-zA-Z0-9_]+$");
        Matcher m = p.matcher(pass);
        return m.matches();
    }

    /**
     * 6-18位
     * 验证密码错误返回信息
     *
     * @param pass
     * @return
     */
    public static String isPassString(String pass) {
        if (pass.length() < 6 || pass.length() > 18) {
            return "密码长度限制为6-18位";
        }
        Pattern p = Pattern.compile("^[a-zA-Z0-9_]+$");
        Matcher m = p.matcher(pass);
        if (!m.matches()) {
            return "密码必须为数字、字母、或下划线";
        }
        return "";
    }

    /**
     * 6-18位 自少一个字母
     *
     * @param pass
     * @return
     */
    public static boolean isPass1(String pass) {
        Pattern p = Pattern.compile("^(?![^a-zA-Z]+$).{6,18}$");
        Matcher m = p.matcher(pass);
        return m.matches();
    }

    /**
     * 只可以输入正数（包括正数和小数）
     *
     * @param price
     * @return
     */
    public static boolean isPrice(String price) {
        Pattern p = Pattern.compile("^[+]?[\\d]+(([\\.]{1}[\\d]+)|([\\d]*))$");
        Matcher m = p.matcher(price);
        return m.matches();
    }

    /**
     * 返回正数（包括正数和小数）否则返回默认值
     *
     * @param str
     * @param defaul
     * @return
     */
    public static float getFloat(String str, float defaul) {
        Pattern p = Pattern.compile("^[+]?[\\d]+(([\\.]{1}[\\d]+)|([\\d]*))$");
        Matcher m = p.matcher(str);
        if (m.matches()) {
            return Float.parseFloat(str);
        } else {
            return defaul;
        }
    }

    /**
     * 返回正整数 ，否则返回默认值
     *
     * @param str
     * @param defaul
     * @return
     */
    public static int getInt(String str, int defaul) {
        Pattern p = Pattern.compile("^[0-9]\\d*$");
        Matcher m = p.matcher(str);
        if (m.matches()) {
            return Integer.parseInt(str);
        } else {
            return defaul;
        }
    }

    /**
     * 邮箱 如：zhangsan@163.com、li-si@236.net、wan_gwu999@SEED.NET.TW
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {
        Pattern p = Pattern
                .compile("^([a-zA-Z0-9]+[_|\\-|\\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\\-|\\.]?)*[a-zA-Z0-9]+(\\.[a-zA-Z]{2,3})+$");
        Matcher m = p.matcher(email);
        return m.matches();
    }

    //邮箱验证
    public static boolean isEmailtow(String strEmail) {
        String strPattern = "^[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$";
        if (TextUtils.isEmpty(strPattern)) {
            return false;
        } else {
            return strEmail.matches(strPattern);
        }
    }

    /**
     * 是否是汉字
     *
     * @param characters
     * @return
     */
    public static boolean isChina(String characters) {
        Pattern p = Pattern.compile("^[\u4e00-\u9fa5]+$");
        Matcher m = p.matcher(characters);
        return m.matches();
    }
    /*
     * 验证书名，汉字，数字，字母，冒号
     *
     * */

    public static boolean verifyBookName(String characters) {
        if (characters.equals("") || characters == null) {
            return true;
        }
        Pattern p = Pattern.compile("^[a-zA-Z0-9\u4e00-\u9fa5，：]+$");
        Matcher m = p.matcher(characters);
        return m.matches();
    }
    /*
     * 验证昵称，汉字，数字，字母，下划线
     *
     * */

    public static boolean verifyUserName(String characters) {
        Pattern p = Pattern.compile("^[a-zA-Z0-9\u4e00-\u9fa5_]+$");
        Matcher m = p.matcher(characters);
        return m.matches();
    }

    /**
     * 简单的身份证号码验证
     *
     * @param idCard
     * @return
     */
    public static boolean isIdCard(String idCard) {
        Pattern p = Pattern.compile("\\d{17}([0-9]|x|X)");
        Matcher m = p.matcher(idCard);
        return m.matches();
    }

    public static String getString(JSONObject object, String key, String defaul) {
        if (defaul == null) {
            defaul = "";
        }
        if (object.has(key)) {
            try {
                return object.get(key) + "";
            } catch (JSONException e) {

                e.printStackTrace();
            }
        }
        return defaul;

    }

    public static String getStringByKeys(JSONObject object, String defaul, String... keys) {
        if (defaul == null) {
            defaul = "";
        }
        for (int i = 0; i < keys.length; i++) {
            String key = keys[i];
            if (object.has(key)) {
                try {
                    return object.get(key) + "";
                } catch (JSONException e) {

                    e.printStackTrace();
                }
            } else {

            }
        }
        return defaul;

    }

    public static JSONObject getJSONObjectByKeys(JSONObject object, String... keys) {
        JSONObject object1 = new JSONObject();
        for (int i = 0; i < keys.length; i++) {
            String key = keys[i];
            if (object.has(key)) {
                try {
                    return object.getJSONObject(key);
                } catch (JSONException e) {

                    e.printStackTrace();
                }
            }
        }
        return object1;

    }

    public static JSONArray getJSONArrayByKeys(JSONObject object, String... keys) {
        JSONArray array = new JSONArray();
        for (int i = 0; i < keys.length; i++) {
            String key = keys[i];
            if (object.has(key)) {
                try {
                    return object.getJSONArray(key);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        return array;

    }

    public static long getLongByKeys(JSONObject object, long defaul, String... keys) {
        for (int i = 0; i < keys.length; i++) {
            String key = keys[i];
            if (object.has(key)) {
                try {
                    return object.getLong(key);
                } catch (JSONException e) {

                    e.printStackTrace();
                }
            }
        }
        return defaul;

    }

    public static int getIntByKeys(JSONObject object, int defaul, String... keys) {
        for (int i = 0; i < keys.length; i++) {
            String key = keys[i];
            if (object.has(key)) {
                try {
                    return object.getInt(key);
                } catch (JSONException e) {

                    e.printStackTrace();
                }
            }
        }
        return defaul;
    }

    public static int getInt(JSONObject object, String key, int defaul) {
        if (object.has(key)) {
            try {
                return object.getInt(key);
            } catch (JSONException e) {

                e.printStackTrace();
            }
        }
        return defaul;
    }

    public static boolean equals(String s, String... strs) {
        for (int i = 0, size = strs.length; i < size; i++) {
            if (s.equals(strs[i]))
                return true;
        }
        return false;
    }


    /**
     * html 换行  空格 转换并去掉连续的空格和换行
     **/
    public static String getHtmlToString(String str) {
        str = str.replace("<br />", "\n").replace("&nbsp;", " ")
                .replace("  ", " ").replace("   ", " ").replace("    ", " ")
                .replace("\n\n", "\n").replace("\n\n\n", "\n").replace("\n\n\n\n", "\n");
        return str;
    }

    /*
     * 发布章节字数统计，不统计空格
     * */
    public static int getNumChapter(String str) {
        str = str.replace(" ", "").replaceAll("　", "");
        return str.length();
    }

    /*
     * 一键排版
     * */
    public static String getPaibanChapter(String chapter) {
        chapter = chapter.trim();
        chapter = "        " + chapter.replaceAll("　", "  ").replaceAll(" {0,}\n {0,}", "\n").replaceAll("&nbsp;", "").replaceAll("\n{1,}", "\n        ");
        if (chapter.startsWith("\n")) {
            chapter = chapter.substring(1);
        }
        return ToSBC(chapter);
    }

    /**
     * 转半角的函数(DBC case)<br/><br/>
     * 全角空格为12288，半角空格为32
     * 其他字符半角(33-126)与全角(65281-65374)的对应关系是：均相差65248
     *
     * @param input 任意字符串
     * @return 半角字符串
     */
    public static String ToSBC(String input) {
        //半角转全角：
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if ((c[i] > 65295 && c[i] < 65306) || (c[i] > 65312 && c[i] < 65339) || (c[i] > 65344 && c[i] < 65371)) {
                c[i] = (char) (c[i] - 65248);
            }
        }
        //其他字符半角(33-126)与全角(65281-65374)的对应关系是：均相差65248

        return new String(c);
    }

    /*
     * 转换成以万为单位
     * */
    public static String getClicknum(int num) {
        String str = "";
        if (num > 1000) {
            Double aDouble = (double) num / 10000;
            str = String.format("%.1f", aDouble) + "W";
        } else {
            str = "0.1w";
        }
        return str;
    }

    /*
     * 四舍五入
     * */
    public static int getIntnum(double num) {
        // 方式三：
        @SuppressLint("DefaultLocale") String result = String.format("%.0f", num);
// %.2f %. 表示 小数点前任意位数 2 表示两位小数 格式后的结果为f 表示浮点型。
        return Integer.valueOf(result);
    }

    /*
     * 转换单位
     * */
    @SuppressLint("DefaultLocale")
    public static String getNum(int num) {
        String str = "";
        if (num > 1000) {
            Double aDouble = (double) num / 10000;
            str = String.format("%.1f", aDouble) + "W";
        } else {
            str = String.valueOf(num);
        }
        return str;
    }

    /*
     * 发布章节，去点空格，将换行变成<H><LG>
     * */
    public static String getChapterText(String chapter) {
        chapter = chapter.trim() + "\n";
        chapter = chapter.replaceAll("　", "  ").replaceAll(" {0,}\n {0,}", "\n").replaceAll("&nbsp;", "").replaceAll("\n{1,}", "\n");
        if (chapter.startsWith("\n")) {
            chapter = chapter.substring(1);
        }
        //chapter = ToSBC(chapter);
        chapter = chapter.replaceAll("\n", "<H><LG>");
        return chapter;
    }

    /*
     * 发布章节，去点空格，获取字数
     * */
    public static String getChapterTextLength(String chapter) {
        chapter=chapter.replaceAll("<H><LG>","\n");
//中文单词
        String cn_words = chapter.replaceAll("[^\\u4e00-\\u9fa5\\uF900-\\uFA2D\\u3040-\\u309F\\u30A0-\\u30FF，。《》？；’‘：“”【】、…￥！·～＠＃＄％＾＆＊（）＿－—＝＇＋｛｝｜＂＞＜．ｑｗｅｒｔｙｕｉｏｐａｓｄｆｇｈｊｋｌｚｘｃｖｂｎｍＱＷＥＲＴＹＵＩＯＰＡＳＤＦＧＨＪＫＬＺＸＣＶＢＮＭ１２３４５６７８９０]", "");
        int cn_words_count = cn_words.length();
//非中文单词
        String non_cn_words = chapter.replaceAll("[^a-zA-Z0-9`=\';.,/~!@#$%^&*_+|}{\":><?\\[\\]ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩ\\-]", " ");
        int non_cn_words_count = 0;
        String[] ss = non_cn_words.split(" ");
        for(String s:ss){
            if(s.trim().length()!=0) non_cn_words_count++;
        }
//中文和非中文单词合计
        /*chapter = chapter.trim() + "\n";
        chapter = chapter.replaceAll("　", "  ").replaceAll(" {0,}\n {0,}", "\n").replaceAll("&nbsp;", "").replaceAll("\n{1,}", "\n").replaceAll("<H><LG>", "\n");*/
        return  String.valueOf(cn_words_count + non_cn_words_count);
    }

    /*
     * 阅读页取出章节，去点空格，将uuid转换成换行
     * */
    public static String getChaptertext(String chapter) {

        return "        " + chapter.replaceAll("<LG>[a-zA-Z\\d-]{36}</LG>", "\n        ");
    }

    /*
     * 取出章节，去点空格，将uuid转换成换行
     * */
    public static String getChapterContext(String chapter) {

        return "        " + chapter.replaceAll("<LG>[a-zA-Z\\d-]{36}</LG>", "\n        ");
    }

    /*
     * 取出存稿，修理字符串
     *
     * */
    public static String getCungaoChapter(String chapter) {
        chapter = chapter.replaceAll("<H><LG>", "\n").replaceAll("\n{1,}", "\n");
        if (chapter.endsWith("\n")) {
            chapter = chapter.substring(0, chapter.length() - 1);
        }
        return "    " + chapter.replaceAll("\n", "\n         ");
    }

    /*
     * 简介，修理字符串
     * */
    public static String getJianjieText(String jiajietext) {
        jiajietext = jiajietext.replaceAll("\n{1,}", "\n");
        if (jiajietext.startsWith("\n")) {
            jiajietext = jiajietext.substring(1);
        }
        return jiajietext;
    }

    /*
     * 作者的话，修理字符串
     * */
    public static String getAuthorsayText(String jiajietext) {
        if (isEmpty(jiajietext)) {
            jiajietext = "作者什么都没说";
        }
        jiajietext = jiajietext.replaceAll("\n{1,}", "\n");
        if (jiajietext.startsWith("\n")) {
            jiajietext = jiajietext.substring(1);
        }
        if (jiajietext.equals("作者的话：限字200")) {
            jiajietext = "作者什么都没说";
        }
        return jiajietext;
    }

    /**
     * 判断给定字符串是否空白串 空白串是指由空格、制表符、回车符、换行符组成的字符串 若输入字符串为null或空字符串，返回true
     */
    public static boolean isEmpty(CharSequence input) {
        if (input == null || "".equals(input))
            return true;
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
                return false;
            }
        }
        return true;
    }

    /*
     * 支付宝还是微信
     * */
    public static String getType(int type) {
        String s = "";
        switch (type) {
            case 110:
                return "支付宝";
            case 111:
                return "微信";
            case 113:
                return "微信";
            case 112:
                return "iphone内购";
        }
        return "不清楚";
    }

    /*
     * 手机号区号去掉+
     * */
    public static String deletadd(String quhao) {
        if (quhao != null) {
            if (quhao.equals("+86")) {
                return "";
            } else {
                return quhao.replace("+", "");
            }
        }
        return "";
    }
    /*
     * 手机号区号去掉+
     * */

    /*
     * 手机号区号获取type，国内注册为RegisterPwd，找回为findPwd,国际为International,update未修改手机号
     * */
    public static String huoqugettype(String quhao, String type) {
        if (quhao != null) {
            if (quhao.equals("+86")) {
                return type;
            } else if (type.equals("update")) {
                return "LnternationalUpdate";

            } else {
                return "International";
            }
        }
        return "";
    }
    /*
     * 手机号区号去掉+
     * */

    /*
     * 手机号区号获取type，国内注册为RegisterPwd，找回为findPwd,国际为International
     * */
    public static String huoqugettypebangding(String quhao, String type) {
        if (quhao != null) {
            if (quhao.equals("+86")) {
                return type;
            } else {
                return "LnternationalbangDing";
            }
        }
        return "";
    }

    /*
     * 验证手机号是否为170或者171
     * */
    public static boolean isxuniphone(String strphone) {
        if (strphone.length() < 3) {
            return true;
        }
        if (strphone.substring(0, 3).equals("170") || strphone.substring(0, 3).equals("171")) {
            return true;
        }
        return false;


    }

    /*
     * 获取渠道标识
     * */
    public static String getChannelName(Activity ctx) {
        if (ctx == null) {
            return null;
        }
        String channelName = null;
        try {
            PackageManager packageManager = ctx.getPackageManager();
            if (packageManager != null) {
                //注意此处为ApplicationInfo 而不是 ActivityInfo,因为友盟设置的meta-data是在application标签中，而不是某activity标签中，所以用ApplicationInfo
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(ctx.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        channelName = applicationInfo.metaData.get("UMENG_CHANNEL") + "";
                    }
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (channelName.isEmpty()) {
            channelName = "LG20180608000";
        }
        return channelName;
    }
}
